<template>
  <div class="permission-container">
    <!-- 背景装饰元素 -->
    <div class="decoration-circle decoration-circle-1"></div>
    <div class="decoration-circle decoration-circle-2"></div>
    <div class="decoration-circle decoration-circle-3"></div>

    <!-- 搜索区域 -->
    <transition name="fade" appear>
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" class="form" :model="searchForm">
          <el-form-item label="权限搜索:">
            <el-input
              placeholder="请输入权限名称"
              v-model="searchForm.name"
              clearable
              prefix-icon="Search"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="default"
              @click="getPermissionList"
              icon="Search"
            >
              查询
            </el-button>
            <el-button
              type="info"
              size="default"
              @click="resetSearch"
              icon="RefreshRight"
            >
              重置
            </el-button>
            <el-button
              type="success"
              size="default"
              @click="handleAdd"
              icon="Plus"
            >
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </transition>

    <!-- 数据表格 -->
    <transition name="slide-fade" appear>
      <el-card class="table-card" shadow="hover">
        <el-table
          v-loading="loading"
          :data="permissionList"
          border
          style="width: 100%"
          stripe
          highlight-current-row
          class="permission-table"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
          />
          <el-table-column prop="name" label="权限名称">
            <template #default="{ row }">
              <div class="permission-name-cell">
                <el-icon><Key /></el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="权限编码">
            <template #default="{ row }">
              <el-tag size="small" effect="plain">{{ row.code }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="权限描述">
            <template #default="{ row }">
              <el-tooltip
                :content="row.description"
                placement="top"
                :show-after="500"
              >
                <div class="description-cell">{{ row.description }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              <div class="time-cell">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatTime(row.createTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template #default="{ row }">
              <div class="time-cell">
                <el-icon><Timer /></el-icon>
                <span>{{ formatTime(row.updateTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-tooltip content="编辑权限" placement="top">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEdit(row)"
                    icon="Edit"
                  >
                    编辑
                  </el-button>
                </el-tooltip>
                <el-popconfirm
                  :title="`确定要删除权限 '${row.name}' 吗?`"
                  width="260px"
                  @confirm="handleDelete(row)"
                  icon="WarningFilled"
                  icon-color="#F56C6C"
                >
                  <template #reference>
                    <el-tooltip content="删除权限" placement="top">
                      <el-button type="danger" size="small" icon="Delete">
                        删除
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
          v-model:current-page="pageParams.page"
          v-model:page-size="pageParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </el-card>
    </transition>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :before-close="handleDialogClose"
      draggable
      destroy-on-close
    >
      <el-form
        :model="permissionForm"
        :rules="rules"
        ref="permissionFormRef"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input
            v-model="permissionForm.name"
            placeholder="请输入权限名称"
            prefix-icon="Key"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input
            v-model="permissionForm.code"
            placeholder="请输入权限编码"
            prefix-icon="Document"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            placeholder="请输入权限描述"
            rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose" icon="Close">取 消</el-button>
          <el-button type="primary" @click="submitForm" icon="Check">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { formatTime } from '@/util/time.ts'
import {
  reqPermissionPage,
  reqAddPermission,
  reqUpdatePermission,
  reqDeletePermission,
  type Permission,
} from '@/api/acl/permission/index.ts'

// 加载状态
const loading = ref(false)

// 权限列表数据
const permissionList = ref<Permission[]>([])
const total = ref(0)

// 分页参数
const pageParams = reactive({
  page: 1,
  limit: 10,
})

// 搜索表单
const searchForm = reactive({
  name: '',
})

// 重置搜索条件
const resetSearch = () => {
  searchForm.name = ''
  getPermissionList()
}

// 获取权限列表数据
const getPermissionList = async () => {
  loading.value = true
  try {
    const res = await reqPermissionPage(
      pageParams.page,
      pageParams.limit,
      searchForm,
    )
    if (res.code === 1) {
      permissionList.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表出错:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageParams.limit = val
  pageParams.page = 1
  getPermissionList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  pageParams.page = val
  getPermissionList()
}

// 权限表单相关
const dialogVisible = ref(false)
const dialogTitle = computed(() =>
  permissionForm.id ? '编辑权限' : '新增权限',
)
const permissionFormRef = ref()
const permissionForm = reactive<Permission>({
  name: '',
  code: '',
  description: '',
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' },
  ],
}

// 重置表单
const resetForm = () => {
  permissionForm.id = undefined
  permissionForm.name = ''
  permissionForm.code = ''
  permissionForm.description = ''
}

// 处理新增权限
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 处理编辑权限
const handleEdit = (row: Permission) => {
  Object.assign(permissionForm, row)
  dialogVisible.value = true
}

// 处理删除权限
const handleDelete = (row: Permission) => {
  if (!row.id) return

  // 使用 ElPopconfirm 替代此处的确认框
  reqDeletePermission(row.id as number)
    .then((res) => {
      if (res.code === 1) {
        ElMessage.success('删除成功')
        getPermissionList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
    .catch((error) => {
      console.error('删除权限出错:', error)
      ElMessage.error('删除失败')
    })
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const submitForm = async () => {
  if (!permissionFormRef.value) return

  await permissionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const isEdit = !!permissionForm.id
      try {
        const apiMethod = isEdit ? reqUpdatePermission : reqAddPermission
        const res = await apiMethod(permissionForm)

        if (res.code === 1) {
          ElMessage.success(isEdit ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          getPermissionList()
        } else {
          ElMessage.error(res.msg || (isEdit ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error(isEdit ? '编辑权限出错:' : '新增权限出错:', error)
        ElMessage.error(isEdit ? '编辑失败' : '新增失败')
      }
    }
  })
}

// 页面加载时获取权限列表
onMounted(() => {
  getPermissionList()
})
</script>

<style scoped>
.permission-container {
  padding: 20px;
  min-height: calc(100vh - 100px);
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
}

/* 装饰圆圈 */
.decoration-circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.5;
  z-index: 0;
}

.decoration-circle-1 {
  width: 300px;
  height: 300px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  top: -100px;
  right: -100px;
  filter: blur(60px);
  animation: float 8s ease-in-out infinite;
}

.decoration-circle-2 {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, #3b82f6 0%, #2dd4bf 100%);
  bottom: -50px;
  left: -50px;
  filter: blur(40px);
  animation: float 10s ease-in-out infinite 1s;
}

.decoration-circle-3 {
  width: 150px;
  height: 150px;
  background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%);
  top: 40%;
  left: 60%;
  filter: blur(50px);
  animation: float 12s ease-in-out infinite 2s;
}

.search-card,
.table-card {
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.5);
  overflow: hidden;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.permission-table {
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格内容样式 */
.permission-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.description-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

/* 动画效果 */
@keyframes float {
  0%,
  100% {
    transform: translateY(0) scale(1);
  }
  50% {
    transform: translateY(-20px) scale(1.05);
  }
}

.fade-enter-active,
.fade-leave-active {
  transition:
    opacity 0.6s ease,
    transform 0.6s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.slide-fade-enter-active {
  transition: all 0.5s cubic-bezier(0.19, 1, 0.22, 1);
}

.slide-fade-leave-active {
  transition: all 0.5s cubic-bezier(0.19, 1, 0.22, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(30px);
  opacity: 0;
}

/* 添加响应式调整 */
@media screen and (max-width: 768px) {
  .permission-container {
    padding: 10px;
  }

  .form {
    flex-direction: column;
    align-items: stretch;
  }

  .action-buttons {
    flex-direction: column;
    gap: 5px;
  }

  .pagination {
    flex-wrap: wrap;
  }
}
</style>
